package 合并区间;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class Solution
{
    public int[][] merge(int[][] intervals)
    {
        //思路，先对二维数组排序，以左区间为比较标准，然后依次判断是否前一个区间的right>=后一个区间的left
        //是的话更新前一个区间的right，不是说明是两个不同的区间。把后面区间存进去
        //判断输入
        if (intervals.length<2)
            return intervals;

//        Arrays.sort(intervals,(int[] p1,int[] p2)->Integer.valueOf(p1[0]).compareTo(Integer.valueOf(p2[0])));
//        Arrays.sort(intervals, Comparator.comparing((int[] p) -> Integer.valueOf(p[0])));
//        Arrays.sort(intervals, Comparator.comparing( p-> Integer.valueOf(p[0])));
        Arrays.sort(intervals, Comparator.comparingInt(o->o[0]));

        ArrayList<int[]> res = new ArrayList<>();
        res.add(intervals[0]);

        for (int i = 1; i < intervals.length; i++)
        {
            int[] current=intervals[i];
            int [] peek=res.get(res.size()-1);
            if (current[0]>peek[1])
                res.add(current);
            else peek[1]=Math.max(current[1],peek[1]);

        }
        return res.toArray(new int[res.size()][]);
    }

    public static void main(String[] args)
    {

    }
}
// Collections.sort(personList, (Person p1, Person p2) -> p1.getSurName().compareTo(p2.getSurName()));
